package com.qf.controller;

import com.alibaba.druid.util.StringUtils;
import com.qf.annotations.RequestMapping;
import com.qf.pojo.TbUser;
import com.qf.service.Impl.UserServiceImpl;
import com.qf.service.UserService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@RequestMapping("/user")
public class UserServlet {
    private UserService userService = new UserServiceImpl();


@RequestMapping(("/logout"))
    public String logOut(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().invalidate();
            return "redirect:/index.jsp";
    }

    @RequestMapping(("/login"))
    public String login(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        String cod = (String) request.getSession().getAttribute("code");
        if (StringUtils.isEmpty(cod)||!code.equalsIgnoreCase(cod)){
            response.setContentType("text/html;charset=utf-8");
            return "验证码错误";

        }
        TbUser login = userService.login(username,password);
        if (login==null){
            response.setContentType("text/html;charset=utf-8");
            return "用户名或密码错误";

        }
        request.getSession().setAttribute("loginUser", login);
        return "redirect:/index.jsp";
    }
@RequestMapping("/register")
    public String register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            TbUser user = new TbUser();
            Map<String, String[]> parameterMap = request.getParameterMap();
            BeanUtils.populate(user, parameterMap);
            String repeatpassword = request.getParameter("repeatpassword");
            if (StringUtils.isEmpty(repeatpassword) || !repeatpassword.equals(user.getPassword())) {
                request.setAttribute("msg", "两次输入密码不一致");
                return "forward:/error/fail.jsp";
            }
            userService.addUser(user);
            return "redirect:/registerSuccess.jsp";
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            request.getSession().setAttribute("msg", e.getMessage());
            return "redirect:/error/fail.jsp";
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            return "redirect:/error/error.jsp";
        }
    }


}
